package main

import "fmt"

func firstTime() {
	fmt.Println("start")

	configPath := "/go/src/fabric_client/config.yaml"

	channelInfo := NewChannelInfo("businesschannel", "/tmp/channel-artifacts/businesschannel.tx")

	org1Info := NewOrganizationInfo("Admin", "Org1")
	ordererInfo := NewOrdererInfo("Admin", "orderer0.example.com", org1Info)
	fabricClient := NewFabricClient(configPath, ordererInfo, "Org1MSP")

	peer0Org1Info := NewPeerInfo("peer0", "peer0.org1.example.com", org1Info)

	// 创建channel
	if err := fabricClient.CreateChannel(channelInfo, ordererInfo, org1Info); err != nil {
		fmt.Println(err)
	}

	ccInfo := NewChaincodeInfo("/go/src/chaincodes", "exp02")
	// peer1Org1Info := NewPeerInfo("peer1", "peer1.org1.example.com", org1Info)

	// 节点加入并安装链码
	if err := fabricClient.JoinChannel(channelInfo.ChannelId, peer0Org1Info); err != nil {
		fmt.Println(err)
	}
	_ = fabricClient.InstallChaincode(channelInfo.ChannelId, peer0Org1Info, ccInfo)

	// 初始化
	if err := fabricClient.InitCC(channelInfo.ChannelId, ccInfo.Label, peer0Org1Info); err != nil {
		fmt.Println(err)
	}

	// 可以先不装，这个装了的话后面addOrg2会更复杂些，现在写的代码没有集成多个peer
	// // 另一个节点加入并安装链码
	// if err := fabricClient.JoinChannel(channelInfo.ChannelId, peer1Org1Info); err != nil {
	// 	fmt.Println(err)
	// }
	// // 更新时sequence需要+1
	// ccInfo.Sequence++
	// _ = fabricClient.InstallChaincode(channelInfo.ChannelId, peer1Org1Info, ccInfo)
}

func addOrg2() {
	fmt.Println("start")

	// 还需要根据之前的config.yaml与org2.yaml获取最新的config_org2.yaml
	configPath := "/go/src/fabric_client/config_org2.yaml"
	channelId := "businesschannel"

	org2Info := NewOrganizationInfo("Admin", "Org2")
	ordererInfo := NewOrdererInfo("Admin", "orderer0.example.com", org2Info)

	fabricClient := NewFabricClient(configPath, ordererInfo, "Org1MSP")
	peer0Org2Info := NewPeerInfo("peer0org2", "peer0.org2.example.com", org2Info)

	if err := fabricClient.JoinChannel(channelId, peer0Org2Info); err != nil {
		fmt.Println(err)
	}

	ccInfo := NewChaincodeInfo("/go/src/chaincodes", "exp02")

	peer0Org1Info := NewPeerInfo("peer0", "peer0.org1.example.com", NewOrganizationInfo("Admin", "Org1"))
	fabricClient.FillCCVersionAndSequence(peer0Org1Info, channelId, ccInfo)
	ccInfo.Sequence++
	fmt.Println("cc version: ", ccInfo.Sequence)

	_ = fabricClient.InstallChaincodeToNew(channelId, peer0Org1Info, peer0Org2Info, ccInfo)
}

func main() {
	addOrg2()
}
